package com.deep.test.designpattern.proxy;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * <p>Description:自定义classLoader 加载指定的类</p>
 * Created with IDEA
 * author:hudepin
 * createTime:2018/5/22 13:34
 */
public class DpClassLoader extends ClassLoader{
    private File classPathFile;

    public DpClassLoader() {
        String classPath = DpClassLoader.class.getResource("").getPath();
        classPathFile = new File(classPath);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = DpClassLoader.class.getPackage().getName()+"."+name;
        if(classPathFile!=null){
            File classFile = new File(classPathFile,name.replaceAll("\\.","/")+".class");
            if(classFile.exists()){
                FileInputStream fis = null;
                ByteArrayOutputStream bos = null;
                try{
                    fis = new FileInputStream(classFile);
                    bos = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024];
                    int len = 0;
                    while((len = fis.read(buff))!=-1){
                        bos.write(buff,0,len);
                    }
                    return defineClass(className,bos.toByteArray(),0,bos.size());
                }catch(Exception e){}
            }
        }
        return super.findClass(name);
    }
}
